//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    community:'',
    token:'',
    search_key: '',
    functionList: [
      {
        "title":"美食",
        "url":"https://z3.ax1x.com/2021/05/26/29Zz9S.png",
        category: 1
      },
      {
        "title":"便利店",
        "url":"https://z3.ax1x.com/2021/05/27/2CwAud.png",
        category: 2
      },
      {
        "title":"蔬果生鲜",
        "url":"https://z3.ax1x.com/2021/05/27/2CwVHI.png",
        category: 3
      },
      {
        "title":"社区帮购",
        "url":"https://z3.ax1x.com/2021/05/30/2Vkwod.png",
        category: 4
      },
      {
        "title":"娱乐",
        "url":"https://z3.ax1x.com/2021/05/31/2egNuQ.png",
        category: 5
      },
    ],
    community: '',
    city: '',
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    showFixed: false,
    sortHeight: 0,
    sortIndex: 0,
    sortListIndex: 0,
    showSort: false,
    scrollFixedTop: 0,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    storeList: undefined,
    storeList1: [{
      storeId: 1,
      storeName: '竹林香米线',
      storeImgUrl: 'https://z3.ax1x.com/2021/05/12/gw15o6.jpg',
      score: 4.4,
      saleMonth: 835,
      minDelPrice: 0,
      delPrice: 5,
      averagePrice: 15,
      delTime: 10,
      service: ['支持自取'],
      actives: [{
          activeId: 1,
          acticeText: '满20减10；满200减20；满1000减50；满1000减50'
        },
        {
          activeId: 2,
          acticeText: '本店新用户立减1元'
        },
        {
          activeId: 3,
          acticeText: '折扣商品9折起'
        }
      ]
    }, {
      storeId: 2,
      storeName: '百科超市',
      storeImgUrl: 'https://z3.ax1x.com/2021/05/12/gw1oFK.jpg',
      score: 3.0,
      saleMonth: 835,
      minDelPrice: 0,
      delPrice: 5,
      averagePrice: 15,
      delTime: 5,
      service: ['支持自取', '货到付款'],
      actives: [{
          activeId: 1,
          acticeText: '满20减10；满200减20'
        },
        {
          activeId: 2,
          acticeText: '本店新用户立减1元'
        }
      ]
    }, {
      storeId: 3,
      storeName: '肯德基',
      storeImgUrl: 'https://z3.ax1x.com/2021/05/12/gw1he1.jpg',
      score: 3.0,
      saleMonth: 835,
      minDelPrice: 0,
      delPrice: 5,
      averagePrice: 15,
      delTime: 10,
      service: ['支持自取', '货到付款'],
      actives: [{
          activeId: 1,
          acticeText: '满20减10；满200减20'
        },
        {
          activeId: 2,
          acticeText: '本店新用户立减1元'
        }, {
          activeId: 3,
          acticeText: '折扣商品9折起'
        }, {
          activeId: 4,
          acticeText: '折扣商品9折起'
        }
      ]
    }, {
      storeId: 4,
      storeName: '星星理发店',
      storeImgUrl: 'https://z3.ax1x.com/2021/05/12/gw14dx.jpg',
      score: 3.0,
      saleMonth: 835,
      minDelPrice: 0,
      delPrice: 0,
      averagePrice: 30,
      delTime: 10,
      service: ['货到付款'],
      actives: [{
          activeId: 1,
          acticeText: '满20减10；满200减20'
        },
        {
          activeId: 2,
          acticeText: '本店新用户立减1元'
        }
      ]
    }]
  },
  // 顶部搜索栏回车键开始搜索
  confirm(e) {

      var that = this;
      that.data.token = app.getToken()
      //console.log(that.data.token)
      //var communityId = that.data.communityId;
      //网络请求获取账单数据
      wx.request({
        url: 'http://localhost:8080/community/ec/listSearch?name='+e.detail.value,
        method:'GET',
        header:{
          'content-type': 'application/json',
          'Authorization':  that.data.token
        },
        success:function(res){
          // console.log("userInfo" + JSON.stringify(res))
          console.log(res.data);
          that.setData({
            storeList: res.data.data
          });
        },
      }) 
    console.log(e.detail.value)
  },
  //事件处理函数
  onPullDownRefresh: function () {
    console.log('下拉刷新');
    this.initdata();
  },
  onLoad: function () {
    this.loadInfo(); 

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    //this.initdata();
     var that = this;
      that.data.token = app.getToken()
      console.log(that.data.token)
      //网络请求获取账单数据
      wx.request({
        url: 'http://localhost:8080/community/ec/list',
        method:'GET',
        header:{
          'content-type': 'application/json',
          'Authorization':  that.data.token
        },
        success:function(res){
          // console.log("userInfo" + JSON.stringify(res))
          console.log(res.data);
          that.setData({
            storeList: res.data.data
          });
        },
      }) 
      app.sendGetRequest('/community/ec/community', (res) => {
        console.log(res);
        this.setData({
          community: res.msg
        })
      }, (err) => {
        console.log(err.errMsg)
      })

    
  },

  initdata: function(){
      var that = this;
      that.data.token = app.getToken()
      console.log(that.data.token)
      //var communityId = that.data.communityId;
      //网络请求获取账单数据
      wx.request({
        url: 'http://localhost:8080/community/ec/list',
        method:'GET',
        header:{
          'content-type': 'application/json',
          'Authorization':  that.data.token
        },
        success:function(res){
          // console.log("userInfo" + JSON.stringify(res))
          console.log(res.data);
          that.setData({
            storeList: res.data.data
          });
        },
      }) 

  },
  onReady: function (e) {
    // let height;
    // let res = wx.getSystemInfoSync();
    // let winHeight = res.windowHeight;
    // let query = wx.createSelectorQuery();
    // query.select('.tabs').boundingClientRect();
    // query.exec((res) => {
    //   height = res[0].height;
    //   this.setData({
    //     sortHeight: winHeight - height,
    //     scrollFixedTop: res[0].top
    //   })
    // })
  },
  onPageScroll: function (e) {
    if (e.scrollTop >= this.data.scrollFixedTop && !this.data.showFixed) {
      this.setData({
        showFixed: true
      })
    } else if (e.scrollTop < this.data.scrollFixedTop && this.data.showFixed) {
      this.setData({
        showFixed: false
      })
    }
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  select: function(e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: "../store/store?storeId="+id
    })
  },
  banggou() {
    wx.navigateTo({
      url: `../tuan/tuan`
    })
  },
  getTabsInfo(e) {
    wx.pageScrollTo({
      scrollTop: e.target.offsetTop - 1,
      duration: 300
    })
    setTimeout(() => {
      if (e.target.dataset.index == 0) {
        this.setData({
          showSort: !this.data.showSort
        })
      }
      if (e.target.dataset.index) {
        this.setData({
          showFixed: true,
          sortIndex: e.target.dataset.index
        })
      }
    }, 350)
  },
  getFixedTabsInfo(e) {
    if (e.target.dataset.index) {
      this.setData({
        sortIndex: e.target.dataset.index
      })
    }
    if (e.target.dataset.index == 0) {
      this.setData({
        showSort: !this.data.showSort
      })
    } else {
      this.setData({
        showSort: false
      })
    }
  },
  move() {},
  selectSort(e) {
    if (e.target.dataset.sortindex || e.target.dataset.sortindex == 0) {
      this.setData({
        sortListIndex: e.target.dataset.sortindex,
        showSort: false
      })
    } else {
      this.setData({
        showSort: false
      })
    }
  },
  loadInfo: function () {
    var page = this
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标 
      success: function (res) {
        // success 
        var longitude = res.longitude
        var latitude = res.latitude
        //  console.log(longitude + " " + latitude)
        page.loadCity(longitude, latitude)
      },
      fail: function () {// fail 
      },
      complete: function () {
      // complete 
      }
      })
    },
    onFunctionTap: function(e){
      var category = e.currentTarget.dataset.category
      console.log(category)
      switch(category) {
        case 1:
          wx.navigateTo({
            url: '../food/food?category=1',
          })
          break
        case 2:
          wx.navigateTo({
            url: '../food/food?category=2',
          })
          break
        case 3:
          wx.navigateTo({
            url: '../food/food?category=3',
          })
          break
        case 4:
            wx.navigateTo({
              url: '../tuan/tuan',
            })
            break
        case 5:
          wx.showToast({
            title: '敬请期待！',  
            icon: 'success',  
            duration: 1500
           })
              break
  
        default:
          console.log('index: category', category, 'unfinished')
      }
    },
  loadCity: function (longitude, latitude) {
    var page = this
    wx.request({
    url: 'http://api.map.baidu.com/reverse_geocoding/v3/?ak=OntSEtwgrKDTbgiZQDTbdU8UZVYkrIPf&output=json&coordtype=wgs84ll&location=' + latitude + ',' + longitude,
      //这里的ak 是去百度地图api获取的需要自己登陆获取一下 地址：https://lbsyun.baidu.com/index.php?title=wxjsapi
    data: {},
    header: {
      'Content-Type': 'application/json'
    },
    success: function (res) {
      // success 
      console.log(res);
      //  var city = res.data.result.addressComponent.city;
      var city = res.data.result.formatted_address
      console.log("城市为" + city)
      page.setData({ city: city });
    },
    
    fail: function () {
    // fail 
    },
    complete: function () {
    // complete 
    }
    })
  }
})